package com.safewind.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("fileUpload")
public class FileUploadController {

	/***
	 * 上传文件 用@RequestParam注解来指定表单上的file为MultipartFile
	 * 
	 * @param file
	 * @return
	 */
	@RequestMapping("upload")
	public String fileUpload(@RequestParam("file") MultipartFile file,
			HttpServletRequest request, HttpSession session) {
		// 判断文件是否为空
		if (!file.isEmpty()) {
			try {
				// 文件保存路径
				String path = request.getSession().getServletContext()
						.getRealPath("/")
						+ "upload/";
				String filePath = path + file.getOriginalFilename();
				// 转存文件
				File uploadPath = new File(path);
				if (!uploadPath.exists()) {
					uploadPath.mkdirs();
				}
				File f = new File(filePath);
				file.transferTo(f);
				session.setAttribute("file", f);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 重定向
		return "redirect:/address/resolver";
	}

	/***
	 * 读取上传文件中得所有文件并返回
	 * 
	 * @return
	 */
	@RequestMapping("list")
	public ModelAndView list(HttpServletRequest request) {
		String filePath = request.getSession().getServletContext()
				.getRealPath("/")
				+ "upload/";
		ModelAndView mav = new ModelAndView("list");
		File uploadDest = new File(filePath);
		String[] fileNames = uploadDest.list();
		for (int i = 0; i < fileNames.length; i++) {
			// 打印出文件名
			System.out.println(fileNames[i]);
		}
		return mav;
	}
}
